import alertFill from "@/assets/image/icons/alert-fill.svg";
import crossCircle from "@/assets/image/icons/cross-circle.png";
import LGV from "@/assets/image/icons/LGV.svg";
import Motorcycle from "@/assets/image/icons/Motorcycle.svg";
import privatecar from "@/assets/image/icons/privatecar.svg";
import CustomModal from "@/components/customModal";
import UpoladItem from "@/components/upload-item";
import { ProForm } from "@ant-design/pro-components";
import {
  Button,
  Divider,
  Form,
  message,
  Modal,
  Space,
  Table,
  TableProps,
} from "antd";
import React, { useRef, useState } from "react";
import { history } from "umi";
import SubmissionCheckbox from "@/components/lpn-submission-checkbox";
import styles from "./index.less";
import { StyledAgree, StyledCancel } from "@/components/button";
import { StyledTextAlign } from "@/components/common-styled";
import { getLPNSave } from "@/services/lpn-registration";
import { consolidateData } from "./utils";
import { VehicleData } from "./types";
import { CustomSubTitle } from "@/components/customTitle";

interface DataType {
  key: string;
  vehicle_type: string;
  license_plate_number: string;
}

const columns: TableProps<DataType>["columns"] = [
  {
    title: "Vehicle Type",
    dataIndex: "vehicle_type",
    align: "left",
  },
  {
    title: "License Plate Number",
    className: "license_plate_number",
    dataIndex: "license_plate_number",
    align: "left",
  },
];

const data: DataType[] = [
  {
    key: "1",
    vehicle_type: "Private Car",
    license_plate_number: "XC5689",
  },
  {
    key: "2",
    vehicle_type: "Motorcycle",
    license_plate_number: "XC10000",
  },
];

const RegisterDetail: React.FC = () => {
  const [form] = Form.useForm();
  const formRef = useRef(form);
  // 控制确认提交模态框的显示状态
  const [isModalOpenSubmit, setIsModalOpenSubmit] = useState(false);
  // 控制提交失败模态框的显示状态
  const [isModalOpenSubmitFailed, setIsModalOpenSubmitFailed] = useState(false);
  // 是否需要提交状态
  const [isNeedSubmit, setIsNeedSubmit] = useState(false);

  const onFinish = async (values: any) => {
    console.log("Form values=====", values);

    // 处理提交逻辑
    setIsNeedSubmit(true);
    // const licenseNumberKeys = Object.keys(values).filter(
    //   (key) => key.includes("licenseNumber") && values[key] === "123456"
    // );
    // if (licenseNumberKeys.length > 0) {
    //   console.log("Form values2:", values);
    //   setIsModalOpenSubmitFailed(true);
    // } else {
    //   setIsModalOpenSubmit(true);
    // }
  };
  //错误验证拦截
  const onFinishFailed = () => {
    message.error({ content: "please check required field" });
    const firstInvalidField = document.querySelector(
      ".ant-form-item-has-error"
    );
    if (firstInvalidField) {
      firstInvalidField.scrollIntoView({ behavior: "smooth" });
    }
  };

  const handleCancelDeleted = () => {
    form.setFieldValue("privateCar", null);
  };

  const handleCancelDeleted2 = () => {
    form.setFieldValue("motorcycle", null);
  };

  const handleCancelDeleted3 = () => {
    form.setFieldValue("LGV", null);
  };

  const handleClickNext = () => {
    console.log(222222);
    setIsModalOpenSubmit(true);
  };

  // // Submit Modal   submit 提交
  const handleOkSubmit = async () => {
    //处理提交数据
    const formData = form.getFieldsValue();
    console.log(formData, "formData");
    const { privateCar, motorcycle, LGV } = formData;

    // 过滤出有效的车辆数据
    const vehicles = [privateCar, motorcycle, LGV].filter(
      (item) => item !== null && item !== undefined
    ) as VehicleData[];

    try {
      // 等待合并车辆数据
      const result = await consolidateData(vehicles);
      console.log(result, "result");

      // 发起请求
      const data = await getLPNSave(result);
      //@ts-ignore
      if (data?.code === 200) {
        history.push("/register/success");
      } else {
        //@ts-ignore
        message.error(data?.msg);
        setIsModalOpenSubmit(false);
        setIsModalOpenSubmitFailed(true);
      }

      console.log(data, "getLPNList");
    } catch (error) {
      // 处理错误

      // message.error(error?.message);
      console.error(error, "error");
    }
  };

  const handleCancelBtn = () => {
    if (isNeedSubmit) {
      setIsNeedSubmit(false);
    } else {
      history.push("/register");
    }
  };

  const handleCancelSubmit = () => {
    setIsModalOpenSubmit(false);
  };

  const handleOkSubmitFailed = () => {
    setIsNeedSubmit(false);
    setIsModalOpenSubmitFailed(false);
  };

  const handleCancelSubmitFailed = () => {
    setIsModalOpenSubmitFailed(false);
  };

  return (
    <>
      <div className={styles["register"]}>
        <div className={styles["title"]}>Register License Plate Number</div>
        <div className={styles["register-content"]}>
          <ProForm
            initialValues={{}}
            form={form}
            onFinish={onFinish}
            onFinishFailed={onFinishFailed}
            submitter={{
              render: () => (
                <StyledTextAlign>
                  <Space size="large">
                    <StyledCancel
                      type="default"
                      onClick={handleCancelBtn}
                      className={styles["footer-button"]}
                    >
                      Cancel
                    </StyledCancel>
                    <StyledAgree
                      onClick={
                        isNeedSubmit
                          ? handleClickNext
                          : () => formRef.current?.submit()
                      }
                      className={styles["footer-button"]}
                      type="default"
                    >
                      {isNeedSubmit ? "Submit" : "Next"}
                    </StyledAgree>
                  </Space>
                </StyledTextAlign>
              ),
            }}
          >
            <div
              className={styles["license-plate-number-registration"]}
              style={isNeedSubmit ? { pointerEvents: "none" } : {}}
            >
              <CustomSubTitle>License Plate Number Registration</CustomSubTitle>
              <div className={styles["tips-text"]}>
                {" "}
                Each type of vehicle can only be registered once.{" "}
              </div>
              <div>
                <Space
                  style={{ width: "100%" }}
                  size={"middle"}
                  direction="vertical"
                >
                  <UpoladItem
                    clickout={handleCancelDeleted}
                    leftText="Private Car"
                    icon={privatecar}
                    formName="privateCar"
                  />
                  <UpoladItem
                    leftText="Motorcycle"
                    clickout={handleCancelDeleted2}
                    icon={Motorcycle}
                    formName="motorcycle"
                  />
                  <UpoladItem
                    clickout={handleCancelDeleted3}
                    leftText="Large Goods Vehicle"
                    icon={LGV}
                    formName="LGV"
                  />
                </Space>
              </div>
              <Divider plain></Divider>

              <SubmissionCheckbox form={form} checkGroupName="checkGroup" />
            </div>
          </ProForm>
        </div>
      </div>

      {/* Delete Documents modal */}
      {/* <CustomModal
        icon={alertFill}
        title="Delete Documents Type?"
        content="The associated data will be permanently erased."
        onOk={handleOkDeleted}
        onCancel={handleCancelDeleted}
        isModalOpen={isModalOpenDeleted}
        changeShowModal={changeShowModal}
        btnLeftText="Delete"
        btnRightText="Keeping"
      /> */}

      {/* submit modal */}
      <CustomModal
        icon={alertFill}
        title="Confirm to Submit?"
        content=""
        onOk={handleOkSubmit}
        onCancel={handleCancelSubmit}
        isModalOpen={isModalOpenSubmit}
        btnLeftText="Cancel"
        btnRightText="Confirm"
      />

      {/* submitted Failed modal */}
      <Modal
        width={"50%"}
        className="submitted-Failed-Modal"
        height={"80%"}
        title=""
        centered
        open={isModalOpenSubmitFailed}
        footer={null}
        onCancel={handleCancelSubmitFailed}
      >
        <div className={styles["modal-header"]}>
          <img className={styles["modal-icon"]} src={crossCircle} alt="icon" />
          <div className={styles["modal-title"]}>Submission Failed</div>
        </div>
        <div className={styles["modal-content"]}>
          <div className={styles["content-header-text"]}>
            The following license plate numbers have been registered:
          </div>
          {data.map((item, index) => (
            <Table
              key={index}
              columns={columns}
              dataSource={Array.from([item])}
              bordered={false}
              pagination={false}
            />
          ))}
          <div className={styles["content-footer-text"]}>
            Please submit with another vehicle type and license plate number.
          </div>
        </div>
        <div className={styles["button-group"]}>
          <Space size={"large"}>
            <Button
              type="dashed"
              onClick={handleOkSubmitFailed}
              className={styles["footer-button"]}
            >
              Continue Editing
            </Button>
          </Space>
        </div>
      </Modal>
    </>
  );
};

export default RegisterDetail;
